import { defineStore } from 'pinia'
import axios from 'axios'

// 配置axios基础URL
axios.defaults.baseURL = 'http://127.0.0.1:5001'

export const useAuthStore = defineStore('auth', {
  state: () => ({
    user: null,
    token: localStorage.getItem('token') || null,
    menus: []
  }),

  getters: {
    isAuthenticated: (state) => !!state.token,
    userInfo: (state) => state.user,
    userMenus: (state) => state.menus
  },

  actions: {
    async login(credentials) {
      try {
        const response = await axios.post('/api/auth/login', credentials)
        const { access_token, user } = response.data
        
        this.token = access_token
        this.user = user
        
        localStorage.setItem('token', access_token)
        axios.defaults.headers.common['Authorization'] = `Bearer ${access_token}`
        
        return { success: true, message: '登录成功' }
      } catch (error) {
        return { 
          success: false, 
          message: error.response?.data?.message || '登录失败' 
        }
      }
    },

    async register(userData) {
      try {
        const response = await axios.post('/api/auth/register', userData)
        return { success: true, message: response.data.message }
      } catch (error) {
        return { 
          success: false, 
          message: error.response?.data?.message || '注册失败' 
        }
      }
    },

    async getCurrentUser() {
      try {
        const response = await axios.get('/api/auth/me')
        this.user = response.data.user
        this.menus = response.data.menus || []
        return { success: true }
      } catch (error) {
        this.logout()
        return { success: false }
      }
    },

    logout() {
      this.user = null
      this.token = null
      this.menus = []
      localStorage.removeItem('token')
      delete axios.defaults.headers.common['Authorization']
    },

    async initAuth() {
      if (this.token) {
        axios.defaults.headers.common['Authorization'] = `Bearer ${this.token}`
        // 确保获取用户信息和菜单
        try {
          await this.getCurrentUser()
        } catch (error) {
          console.warn('初始化时获取用户信息失败，清理认证状态')
          this.logout()
        }
      }
    }
  }
})